<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="my">我的</el-menu-item>
      <el-menu-item index="share">师徒</el-menu-item>
      <el-menu-item index="department" v-if="legionTrialList">军团</el-menu-item>
      <el-menu-item index="all" v-if="allTrialList">全部</el-menu-item>
    </el-menu>

    <div style="margin-top: 40px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="120px">
        <el-form-item label="客户名称：">
          <el-autocomplete
                  clearable
                  class="inline-input"
                  value-key="customerName"
                  :fetch-suggestions="querySearch"
                  v-model="listQuery.customerName"
                  placeholder="请输入内容"
                  @select="handleSelectCustomerName"
                  :trigger-on-focus="false"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="产品线：">
          <el-select v-model="listQuery.goodsLineId" filterable clearable>
            <el-option :label="item.cddValue" v-for="item in goodsLineList" :value="item.cddId" :key="item.cddId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="牌号：">
          <el-select v-model="listQuery.goodsSn" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in goodsList"
              :key="item.kingId"
              :label="item.goodsSn"
              :value="item.goodsSn">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请日期：">
          <el-date-picker
            :default-time="['00:00:00']"
            v-model="listQuery.tryTime"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="业务员：" v-if="listQuery.tab!='my'">
          <el-select v-model="listQuery.tryUserId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试样结果：">
          <el-select v-model="listQuery.tryResult" class="input-width" style="width:195px" placeholder="请选择" clearable>
            <el-option  :value="item.cddId" :label="item.cddValue" v-for="item in resultList" :key="item.cddId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品匹配度：">
          <el-select v-model="listQuery.tryMatch" class="input-width" style="width:195px" placeholder="请选择" clearable>
            <el-option  :value="item.cddId" :label="item.cddValue" v-for="item in matchList" :key="item.cddId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="listQuery.checkState" class="input-width" style="width:195px" placeholder="请选择" clearable>
            <el-option :value="item.key" :label="item.name" :key="item.key" v-for="item in checkStateList"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
          <el-button
            v-if="listQuery.tab=='all'&& exportTrialList"
            @click="downloadExcel()"
            type="primary">
            导出
          </el-button>
          <el-button
            @click="showpop('','add')"
            type="primary">
            新增试料
          </el-button>
        </el-form-item>
      </el-form>
    </div>

      <!--数据列表-->
    <div class="table-container">
        <el-table
          v-loading="listLoading"
          :data="tableData"
          border
          style="width: 100%; margin-top: 20px">
          <el-table-column
              label="客户名称"
              min-width="150"
              align="center">
            <template slot-scope="scope">
                 {{scope.row.customerName}}
            </template>
          </el-table-column>
          <el-table-column  label="申请人" min-width="100" align="center">
            <template slot-scope="scope">
                  {{scope.row.tryUserName}}
            </template>
          </el-table-column>
          <el-table-column
              label="产品线"
              min-width="100"
              align="center">
            <template slot-scope="scope">
              {{scope.row.goodsLineName}}
            </template>
          </el-table-column>
          <el-table-column
                label="试样牌号"
                min-width="150"
                align="center">
              <template slot-scope="scope">
                {{scope.row.goodsSn}}
              </template>
          </el-table-column>
          <el-table-column
                label="数量"
                min-width="100"
                align="center">
            <template slot-scope="scope">
              {{scope.row.goodsNum}}
            </template>
          </el-table-column>
          <el-table-column
              label="用料情况"
              min-width="150"
              align="center">
            <template slot-scope="scope">
              {{scope.row.useGoodsInfo}}
            </template>
          </el-table-column>
          <el-table-column
              label="收样信息"
              min-width="150"
              align="center">
            <template slot-scope="scope">
              {{scope.row.receiverName}} / {{scope.row.receiverMobile}} / {{scope.row.addressInfo}}
            </template>
          </el-table-column>
          <el-table-column
            label="申请时间"
            min-width="150">
            <template slot-scope="scope">
              {{scope.row.tryTime}}
            </template>
          </el-table-column>
          <el-table-column
              align="center"
              label="试样结果"
              min-width="100">
            <template slot-scope="scope">
              {{scope.row.tryResult}}
            </template>
          </el-table-column>
          <el-table-column
            label="产品匹配度"
            min-width="100"
            align="center">
            <template slot-scope="scope">
              {{scope.row.tryMatch}}
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            min-width="150"
            align="center">
            <template slot-scope="scope">
              {{scope.row.tryRemark}}
            </template>
          </el-table-column>

          <el-table-column
            label="更新时间"
            min-width="150"
            align="center">
            <template slot-scope="scope">
               {{scope.row.updateTime}}
            </template>
          </el-table-column>
          <el-table-column
            label="操作人"
            min-width="100"
            align="center">
            <template slot-scope="scope">
                {{scope.row.tryUserName}}
            </template>
          </el-table-column>
          <el-table-column
                  label="状态"
                  min-width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.checkState | fifstate}}
            </template>
          </el-table-column>

          <el-table-column
            min-width="150"
            fixed="right"
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="showSee(scope.row)" size="mini">查看</el-button>
              <el-button type="text" @click="showCl(scope.row)" size="mini" v-if="scope.row.isCanHandle == 1 && scope.row.checkState == 0">填写试用结果</el-button>
              <el-button type="text" size="mini"  v-if="scope.row.isCanHandle == 1 && scope.row.checkState == 0" @click="cancelItem(scope.row)">取消</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>
    <addSl ref="addSl" @getList="getList"></addSl>
    <clSl ref="clSl" @getList="getList"></clSl>
    <seeSl ref="seeSl"></seeSl>
  </div>
</template>
<script>
    import {getCustomerOption,orderGoodsList,getOrderUsersList,getCustomerSetting} from '@/api/partner'
    import {developGoodsTryList,developGoodsTryCancel} from '@/api/company'
    import store from '@/store'
    import { mapGetters } from 'vuex'
    import addSl from './components/addSl'
    import clSl from './components/clSl'
    import seeSl from './components/seeSl'
    const defaultListQuery={
      pageNum: 1,
      pageSize: 10,
      tab:'my',
      customerId:'',
      tryUserId:'',
      goodsLineId:'',
      goodsSn:'',
      tryTime:[],
      tryResult:'',
      checkState:'',
      tryMatch:'',
    };
    export default {
      name: "trialList",
      data(){
          return {
              creator:'',
              listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
              tableData: [],
              count: 0,
              listLoading: false,
              userOptionList:[],
              roles:store.getters.roles ? store.getters.roles : [],
              goodsList:[],
              goodsLineList:[],
              resultList:[],
            checkStateList:[{name:'已申请',key:'0'},{name:'已取消',key:'10'},{name:'已试样',key:'20'}],
            matchList:[]
          }
      },
      computed: {
        ...mapGetters([
          'name',
          'mobile',
          'userId'
        ]),
        allTrialList(){
          if(this.roles.indexOf("allTrialList") != -1){
            return true
          }else{
            return false
          }
        },
        legionTrialList(){
          if(this.roles.indexOf("legionTrialList") != -1){
            return true
          }else{
            return false
          }
        },
        exportTrialList(){
          if(this.roles.indexOf("exportTrialList") != -1){
            return true
          }else{
            return false
          }
        },

      },
      created() {
        this.getList();
        this.getUserOptionList();
        this.getCustomerSettingList();
        orderGoodsList().then((res)=>{
          this.goodsList = res.list
        })
      },
      components : {
        addSl,clSl,seeSl
      },
      filters: {
        fifstate(val){
          if(val == 0){
            return '已申请'
          }else if(val == 10){
            return '已取消'
          }else if(val == 20){
            return '已试样'
          }
        },
      },
      methods:{
        //获取客户配置
        getCustomerSettingList(){
          getCustomerSetting().then((res)=>{
            res.forEach((el)=>{
              if(el.cdtCode == 'goods_line'){
                this.goodsLineList = el.data
              }else if(el.cdtCode == 'try_result'){
                this.resultList = el.data
              }else if(el.cdtCode == 'try_match'){
                this.matchList = el.data
              }
            });
          })
        },
        cancelItem(item){
          this.$confirm('确定取消此条记录?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            developGoodsTryCancel({tryId:item.tryId}).then(()=>{
              this.getList();
              this.$message({
                type: 'success',
                message: '已取消!'
              });
            });
          }).catch(() => {

          });
        },

        showSee(item){
          this.$refs.seeSl.showPop(item)
        },
        showCl(item){
          this.$refs.clSl.showPop(item)
        },
        showpop(){
          this.$refs.addSl.showPop()
        },
        //下载excle
        downloadExcel(){
          let params = JSON.parse(JSON.stringify(this.listQuery));
          params.export = 1;
          delete params.pageSize;
          delete params.pageNum
          developGoodsTryList(params).then((res)=>{
            require.ensure([], () => {
              const { export_json_to_excel } = require('sheet/Export2Excel');
              const tHeader = res.title;
              const filterVal = res.columns;
              const list = res.list;
              const data = this.formatJson(filterVal, list);
              export_json_to_excel(tHeader, data, res.fileName);
            })
          })
        },

        //下载表格数据格式化
        formatJson(filterVal, jsonData) {
          return jsonData.map(v => filterVal.map(j => v[j]))
        },

          //获取员工下拉选项
          getUserOptionList(){
            getOrderUsersList().then((res)=>{
                  this.userOptionList = res;
              })
          },

          //客户名称输入匹配
          querySearch(queryString, cb){
            if(queryString && queryString!= '') {
              getCustomerOption({keywords: queryString,tab:this.listQuery.tab == 'my' ? 'my' : ''}).then((res) => {
                cb(res);
              })
            }
          },

          //选择客户名称
          handleSelectCustomerName(item){
              console.log("888888888")
              this.listQuery.customerId = item.customerId;
              this.listQuery.customerName = item.customerName
          },

          /**
           * 切换选择状态
           */
          handleSelect(key, keyPath){
              this.listQuery = JSON.parse(JSON.stringify(defaultListQuery)),
              this.listQuery.tab = key;
              this.handleSearchList();
          },
          handleSizeChange(val){
            this.listQuery.pageNum = 1;
            this.listQuery.pageSize = val;
            this.getList();
          },
          handleCurrentChange(val){
            this.listQuery.pageNum = val;
            this.getList();
          },

          handleSearchList(){
            this.listQuery.pageNum = 1;
            this.getList();
          },

          //获取订单列表
          getList() {
            this.listLoading = true;
            let listQuery = JSON.parse(JSON.stringify(this.listQuery));
            listQuery.customerId = listQuery.customerName == '' ? '' : listQuery.customerId
            developGoodsTryList(listQuery).then(response => {
              this.tableData = response.list;
              this.count = response.count;
              this.listLoading = false;
            }).catch(()=>{
              this.listLoading = false;
            });
          },

      },
    }
</script>

<style scoped lang="scss">
  .upload-div{
    text-align: center;
    position:relative;
    #upload{

      opacity: 0;
      position: absolute;
      z-index: 1;
      width:154px;
      height:40px
    }
  }
  .title-tab{
    border-radius: 8px;
    background: #eee;
    margin-left: 10px;
    display: inline-block;
    vertical-align: middle;
    line-height: 20px;
    padding: 0 5px;
    color: #666;
  }
</style>
